<template>
  <div>
    <canvas ref="canvas" width="800" height="400"></canvas>
  </div>
</template>

<script>
export default {
  name: 'EcgWithCoordinates',
  data() {
    return {
      ecgData: [],
      intervalId: null,
      ctx: null,
      x: 0,
      gridStepX: 50,
      gridStepY: 50
    };
  },
  mounted() {
    const canvas = this.$refs.canvas;
    this.ctx = canvas.getContext('2d');
    this.drawGrid();
    this.startUpdating();
  },
  beforeDestroy() {
    clearInterval(this.intervalId);
  },
  methods: {
    drawGrid() {
      const ctx = this.ctx;
      const canvas = this.$refs.canvas;
      ctx.strokeStyle = '#ccc';
      ctx.lineWidth = 1;

      // 绘制垂直网格线
      for (let x = 0; x < canvas.width; x += this.gridStepX) {
        ctx.beginPath();
        ctx.moveTo(x, 0);
        ctx.lineTo(x, canvas.height);
        ctx.stroke();
      }

      // 绘制水平网格线
      for (let y = 0; y < canvas.height; y += this.gridStepY) {
        ctx.beginPath();
        ctx.moveTo(0, y);
        ctx.lineTo(canvas.width, y);
        ctx.stroke();
      }

      // 绘制坐标轴
      ctx.strokeStyle = 'black';
      ctx.lineWidth = 2;
      ctx.beginPath();
      ctx.moveTo(0, canvas.height / 2);
      ctx.lineTo(canvas.width, canvas.height / 2);
      ctx.moveTo(0, 0);
      ctx.lineTo(0, canvas.height);
      ctx.stroke();

      // 绘制坐标轴刻度和标签
      ctx.font = '12px Arial';
      ctx.fillStyle = 'black';
      for (let x = 0; x < canvas.width; x += this.gridStepX) {
        ctx.fillText(x, x, canvas.height / 2 + 15);
      }
      for (let y = 0; y < canvas.height; y += this.gridStepY) {
        ctx.fillText(y, 5, y - 5);
      }
    },
    drawEcg() {
      const ctx = this.ctx;
      const canvas = this.$refs.canvas;
      ctx.strokeStyle = 'green';
      ctx.lineWidth = 2;
      ctx.beginPath();
      ctx.moveTo(0, canvas.height / 2);
      for (let i = 0; i < this.ecgData.length; i++) {
        ctx.lineTo(this.x + i, canvas.height / 2 + this.ecgData[i]);
      }
      ctx.stroke();
    },
    updateData() {
      const newData = Math.random() * 20 - 10;
      this.ecgData.push(newData);
      if (this.ecgData.length > this.$refs.canvas.width) {
        this.ecgData.shift();
        this.x--;
      }
      this.drawGrid();
      this.drawEcg();
    },
    startUpdating() {
      this.intervalId = setInterval(() => {
        this.updateData();
      }, 100);
    }
  }
};
</script>

<style scoped>
canvas {
  border: 1px solid #ccc;
}
</style>